package m.stock.v1;

import com.google.gson.Gson;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by maojianfeng on 8/8/16.
 */
public class TrendPersister {
    private static Logger logger = Logger.getLogger(TrendPersister.class);
    public static void persist(String intermediateDataLocation,String trendDataLocation,int trendLength){
        try {
            File intermediateDataDir = new File(intermediateDataLocation);
            if(intermediateDataDir.exists()&&intermediateDataDir.isDirectory()){
                File trendDataDir = new File(trendDataLocation);
                if(trendDataDir.exists()){
                    FileUtils.forceDelete(trendDataDir);
                }
                FileUtils.forceMkdir(trendDataDir);

                try {
                    Map<String,Integer> usedNameCountMap = new HashMap<String, Integer>();
                    for(File intermediateDataFile:FileUtils.listFiles(intermediateDataDir, new String[]{"dat"}, false)){
                        String fileContent = FileUtils.readFileToString(intermediateDataFile,"utf-8");
                        if(fileContent!=null){
                            String[] jsonRecords = fileContent.split("\n");
                            List<StockRecord> records = new ArrayList<StockRecord>();
                            for(String jsonRecord:jsonRecords){
                                if(jsonRecord!=null&&!jsonRecord.equals("")){
                                    records.add(new Gson().fromJson(jsonRecord,StockRecord.class));
                                }
                            }
                            List<ResultWrapper> wrappers = TrendFinder.compute(records,trendLength);
                            if(wrappers!=null&&!wrappers.isEmpty()){
//                                logger.debug(wrappers);
                                for(ResultWrapper wrapper:wrappers){
                                    String fileNamePre = wrapper.getStockCode()+"-"+wrapper.getDifference()+"-"+wrapper.getDays()+"-"+wrapper.getType();
                                    Integer usedNameCount = usedNameCountMap.get(fileNamePre);
                                    if(usedNameCount!=null){
                                        usedNameCount ++;
                                        fileNamePre = fileNamePre+"#"+usedNameCount;
                                        usedNameCountMap.put(fileNamePre,usedNameCount);
                                    }
                                    String fileName = fileNamePre+".csv";
                                    String persistFileLocation = trendDataLocation+File.separator+fileName;
                                    logger.debug("persisting:"+fileName);
                                    persistFile(wrapper.getRecords(),persistFileLocation);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }
    private static void wiriteHeader(String fileLocation) throws IOException {
        String header = "日期,股票代码,股票简称,涨跌幅(%),现价(元),macd(diff值),macd(dea值),成交额(元),macd差值\n";
        FileUtils.write(new File(fileLocation),header,"utf-8");
    }
    private static void persistFile(List<StockRecord> records,String fileLocation){
        String data = "";
        for(StockRecord record:records){
            data+=record.getDate()
                    +","+record.getStockCode()
                    +","+record.getStockAbbrName()
                    +","+record.getChg()
                    +","+record.getPrice()
                    +","+record.getMacdDiff()
                    +","+record.getMacdDea()
                    +","+new BigDecimal(record.getTradingVolumn()).toPlainString()
                    +","+record.getMacdComputed()+"\n";
        }
        try {
            wiriteHeader(fileLocation);
            FileUtils.write(new File(fileLocation),data,"utf-8",true);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }
}
